<template>
  <div class="app-container">
    <!--表单-->
    <el-form :inline="true" class="demo-form-inline">

      <el-form-item label="日期">
        <el-date-picker
          v-model="day"
          type="date"
          placeholder="选择要统计的日期"
          value-format="yyyy-MM-dd" />
      </el-form-item>

      <el-form-item label="统计类型">
        <el-select v-model="statType" placeholder="请选择统计类型">
          <el-option label="注册人数" value="register"></el-option>
          <el-option label="订单数" value="order"></el-option>
        </el-select>
      </el-form-item>

      <el-button 
        type="primary"
        icon="el-icon-data-analysis"
        :disabled="btnDisabled"
        @click="create">
        生成数据
      </el-button>
    </el-form>
  </div>
</template>

<script>
import sta from '@/api/admin/sta'
export default {
    data() {
        return {
            day: '',
            statType: 'register', // 默认选择注册人数
            btnDisabled: false
        }
    },
    methods: {
        create() {
            if (!this.day) {
                this.$message.error('请选择日期')
                return
            }
    
            this.btnDisabled = true
            const apiMethod = this.statType === 'register' 
                ? sta.createStaData 
                : sta.createOrderData
            
            apiMethod(this.day)
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success('生成数据成功!')
                        this.$router.push({path: '/sta/show'})
                    } else {
                        this.$message.error(response.message || '生成数据失败')
                    }
                })
                .catch(error => {
                    console.error('生成数据失败:', error)
                    let errorMsg = '生成数据失败'
                    if (error.response) {
                        errorMsg += `: ${error.response.data.message || error.response.statusText}`
                    } else if (error.message) {
                        errorMsg += `: ${error.message}`
                    }
                    this.$message.error(errorMsg)
                })
                .finally(() => {
                    this.btnDisabled = false
                })
        }
    }
}
</script>